import Taro, { Component, useState, useEffect, useCallback } from '@tarojs/taro';
import { View, Button, Text, Image, ScrollView } from '@tarojs/components';
import CardBox from '../../components/card-record';
import Empty from '../../static/public/icon_order.png';
import classnames from 'classnames';
import NavigationBar from '../../components/navigationBar/index';

import './index.scss';
import { CARD_STATUS } from '../../utils/config';
import { exchangedCardList } from '../../services/card';
import { timeFormat } from '../../utils/utils';

const SexSelector = ['男', '女'];
let pageData = {
  page: 1,
  page_number: 10
};
let isMore = true;
const navigationBarHeight = Taro.getStorageSync('navigationBarHeight');

function UsedCardRecord(props) {
  
  const [ usedCardRecordList, setUsedCardRecordList ] = useState([])
  let { type } = props;
  console.log(type, 'type')
  if (type === 1) {
    // 刷新
    pageData.page = 1;
    init()
  } else if (type === 2) {
    // 加载
    loadMore()
  } else if (type === 0) {
    //
  }

  useEffect(() => {
    pageData = {
      page: 1,
      page_number: 10
    };
    isMore = true;
    // init()
  }, [])

  function loadMore() {
    props.onChanged()
    if (isMore) {
      exchangedCardList({
        ...pageData
      }).then(res => {
        res.list.forEach(card => {
          card.time = timeFormat(card.convert_time)
          card.sku = ''
          if (card.has_order_goods) {
            card.has_order_goods.has_order_goods_attr.forEach(item => {
              card.sku += item.goods_sku_attr_name + '；'
            })
          }
        });
        pageData.page++
        isMore = res.list.length < res.total;
        setUsedCardRecordList(usedCardRecordList.concat(res.list))
      })
    }
  }

  function init() {
    props.onChanged()
    exchangedCardList({
      ...pageData
    }).then(res => {
      res.list.forEach(card => {
        card.time = timeFormat(card.convert_time)
        card.sku = ''
        if (card.has_order_goods) {
          card.has_order_goods.has_order_goods_attr.forEach(item => {
            card.sku += item.goods_sku_attr_name + '；'
          })
        }
      });
      pageData.page++
      isMore = res.list.length < res.total;
      setUsedCardRecordList(res.list);
    })
  }

  return (
    <View className='card-record' style={`margin-top: ${navigationBarHeight}`}>
      <NavigationBar text="我的兑换卡记录" />
        <View className="card-list">
        {
          usedCardRecordList.length ? usedCardRecordList.map(card => {
            if (card) return <CardBox key={card.id} time={card.time} number={card.card_no} sku={card.sku} status={CARD_STATUS[card.status]} />
          }) : <View className="empty-box">
            <Image src={Empty} className="empty" />
            <View className="tip">暂无信息</View>
          </View>
        }
        </View>
    </View>
  )
}

UsedCardRecord.config = {
  navigationBarTitleText: '我的兑换卡记录',
}

export default UsedCardRecord;
